package com.jeeplus.modules.api.utils;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

import com.jeeplus.common.utils.MD5Util;
import com.taobao.api.Constants;
import org.apache.commons.codec.digest.DigestUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.net.HttpClientUtil;

import static com.taobao.api.internal.util.TaobaoUtils.encryptMD5;

/**
 * 喵有券和折淘客
 * @author ws
 *
 */
public class MiaoyouquanUtils {
	//喵有券
	private static final String apkey = "9aead88d-60cc-40da-b118-b702749ae6e8";// 秘钥
	public static final String pdname = "17194370528";// 在本平台授权后的拼多多用户名
	public static final String getpddopts = "http://api.web.ecapi.cn/pinduoduo/getPddOpts?";// 获得拼多多opt商品标签列表
//	public static final String getpdditem = "http://api.web.ecapi.cn/pinduoduo/getpdditem?";// 获取拼多多推广商品API
	public static final String getpdditem = "http://api.web.ecapi.cn/pinduoduo/goodsSearch?";//  [新]查询拼多多推广商品API
	public static final String getGoodsDetailInfo = "http://api.web.ecapi.cn/pinduoduo/getGoodsDetailInfo?";//  (重构版)获取商品详细信息
	public static final String getpdditemtgurl = "http://api.web.ecapi.cn/pinduoduo/createItemPromotionUrl?";// 获取拼多多商品推广链接API
	public static final String docreatepddpid = "http://api.web.ecapi.cn/pinduoduo/createPid?";// 创建推广位接口
	public static final String getincrementorderlist = "http://api.web.ecapi.cn/pinduoduo/getOauthIncrementOrderList?";// 按照更新时间段增量同步推广订单信息

	public static final String lmdykey = "adc6e341-6516-3f66-815a-c574c8a00f49";// 京东联盟调用key
	public static final String siteId = "1937737514";// 站点ID（也是京东联盟的APPID）
	public static final String lmsqkey = "ece3b6ab1c8b87a777fb7a7db3c3b5eda34439055a989116836d7313a1c89d07a3b642f4f59e461a";// 京东联盟授权KEY
	public static final String getItemCateInfo = "http://api.web.ecapi.cn/jingdong/getItemCateInfo?";// 京东商品类目查询
	public static final String getJdUnionItems = "http://api.web.ecapi.cn/jingdong/getJdUnionItems?";// 京东商品查询API
	public static final String getItemInfo = "http://api.web.ecapi.cn/jingdong/getItemInfo?";// 获取商品综合信息
	public static final String getItemDesc = "http://api.web.ecapi.cn/jingdong/getItemDesc?";// (重构版)京东商品详情页API
	public static final String createUnionPosition = "http://api.web.ecapi.cn/jingdong/createUnionPosition?";// 创建推广位
	public static final String doItemCpsUrl = "http://api.web.ecapi.cn/jingdong/doItemCpsUrl?";// 创建推广位
	public static final String getJdUnionOrders = "http://api.web.ecapi.cn/jingdong/getJdUnionOrders?";// 创建推广位
	public static final String getJfItems = "http://api.web.ecapi.cn/jingdong/getJfItems?";// 京粉精选商品查询接口
	public static final String doPromotionCommonUrl = "http://api.web.ecapi.cn/jingdong/doPromotionCommonUrl?";//  京东通用转链API
	
	
	//折淘客
	private static final String appkey = "3a2c1071d9244d4482fca19f3ff2202e";// 秘钥
	public static final String sid = "22375";// 授权账号ID
	public static final String pid = "mm_589140146_910450299_109652350334";// PID
	public static final String api_type = "https://api.zhetaoke.com:10001/api/api_type.ashx?";// 一级和二级分类及分类图片：返回一级和二级分类列表，包括分类图片。
	public static final String api_all = "https://api.zhetaoke.com:10001/api/api_all.ashx?";// 返回天猫商品列表，返回佣金≥15%，动态描述分≥4.6的商品列表。
	public static final String open_gaoyongzhuanlian = "https://api.zhetaoke.com:10001/api/open_gaoyongzhuanlian.ashx?";// 高佣转链API（商品ID）
	public static final String api_detail = "https://api.zhetaoke.com:10002/api/api_detail.ashx?";// 高佣转链API（商品ID）
	public static final String open_item_guess_like = "https://api.zhetaoke.com:10001/api/open_item_guess_like.ashx?";// 猜你喜欢API（相似商品API）
	public static final String api_quanwang = "https://api.zhetaoke.com:10003/api/api_quanwang.ashx?";// 全网搜索商品API接口
	public static final String api_pinpai_name = "https://api.zhetaoke.com:10001/api/api_pinpai_name.ashx?";// 品牌列表：返回前100名品牌名列表
	public static final String api_videos = "https://api.zhetaoke.com:10001/api/api_videos.ashx?";// 视频(抖货)商品API接口
	public static final String api_quantian = "https://api.zhetaoke.com:10001/api/api_quantian.ashx?";// 全天销量榜API
	public static final String api_dongdong = "https://api.zhetaoke.com:10001/api/api_dongdong.ashx?";// 咚咚抢商品API接口
	public static final String open_sc_publisher_save = "https://api.zhetaoke.com:10001/api/open_sc_publisher_save.ashx?";// 淘宝客渠道备案API
	public static final String open_dingdanchaxun2 = "https://api.zhetaoke.com:10001/api/open_dingdanchaxun2.ashx?";// 新订单查询API接口
	public static final String api_shishi = "https://api.zhetaoke.com:10001/api/api_shishi.ashx?";// 实时人气榜API
	public static final String open_tkl_create = "https://api.zhetaoke.com:10001/api/open_tkl_create.ashx?";// 淘口令生成API
	public static final String open_shangpin_id = "https://api.zhetaoke.com:10001/api/open_shangpin_id.ashx?";// 解析商品编号API（返回商品ID和券ID）
	public static final String open_activitylink_get = "https://api.zhetaoke.com:10001/api/open_activitylink_get.ashx?";//根据淘宝联盟官方活动ID获取自己的官方活动推广URL
	public static final String open_shorturl_taobao_get = "https://api.zhetaoke.com:10001/api/open_shorturl_taobao_get.ashx?";//淘宝短链转换API
	public static final String api_activity = "https://api.zhetaoke.com:10001/api/api_activity.ashx?";//返回联盟官方活动列表


	//多麦联盟
	private static final String site_key = "6b5c5f58b650d6c05f8a702c2399be21";// 接口秘钥
	private static final String site_id = "273854";// 媒体ID
	private static final String track_aid = "4882";// t
	public static final String track = "https://c.duomai.com/track.php?";// 美团外卖红包推广

	//淘宝
	private static final String app_key = "27969416";// TOP分配给应用的AppKey
	private static final String tb_secret = "f5c90963820165ed1974486880f99606";// TOP分配给应用的AppKey
	public static final String tb_method = "taobao.tbk.order.details.get";// API接口名称
	public static final String details_get = "https://eco.taobao.com/router/rest?";// 美团外卖红包推广


	//多多进宝
	//用POST方式提交
	private static final String client_id = "b585bf2fa72d46a28d0096eaca61d249";// POP分配给应用的client_id
	private static final String client_secret = "61bb49f1c53643a336929d4db1f8c83fd36d6468";// t
	public static final String router = "https://gw-api.pinduoduo.com/api/router?";// 生成多多进宝频道推广
	public static final String urlgen = "pdd.ddk.resource.url.gen";// 生成多多进宝频道推广
	public static final String generate = "pdd.ddk.theme.prom.url.generate";// 多多进宝主题推广链接生成
	public static final String promotion = "pdd.ddk.goods.promotion.url.generate";// 多多进宝主题推广链接生成

	public static void main(String[] args) {
		/*Map<String, String> params = Maps.newHashMap();
		params.put("page", "1");
		params.put("pagesize", "10");
		params.put("coupon", "true");
		params.put("optid", "14");
		params.put("sort", "0");
		JSONObject result =miaoyouquanAPI(getpdditem, params);
		System.out.println(result);
		System.out.println((result.getJSONObject("data").getJSONArray("goods_list")).getJSONObject(0).getString("category_name"));*/
		/*Map<String, String> params = Maps.newHashMap();
		JSONObject result =zetaokeAPI(api_type, params);
		System.out.println(result.getJSONArray("type"));*/
		Map<String, String> params = Maps.newHashMap();
		params.put("pdname", MiaoyouquanUtils.pdname);
		params.put("number", "1");
		JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params);
		System.out.println(jsonObject.getJSONObject("data").getJSONArray("p_id_list").getJSONObject(0).getString("p_id"));
		
	}

	/**
	 * 多多进宝推广链接
	 * @param url API接口路径
	 *            type 接口名字
	 * @param params 业务参数
	 * @return
	 */
	public static JSONObject duoduorouterAPI(String url,String type,Map<String, String> params) {
		params.put("client_id", client_id);
		params.put("type", type);
		long now = new Date().getTime();
		params.put("timestamp", String.valueOf(now/1000));
		String url2 =getDuoduoParams(params);
		String sign = client_secret+url2+client_secret;
		sign = MD5Util.md5(sign).toUpperCase();
		params.put("sign", sign);

		String	resultString = HttpClientUtil.doPost(url,params);
		return StringUtils.isNotBlank(resultString) ? JSONObject.parseObject(resultString) : new JSONObject();
	}

	/**
	 * 淘宝客-推广者-所有订单查询
	 * @param url API接口路径
	 *            type 接口名字
	 * @param params 业务参数
	 * @return
	 */
	public static JSONObject tbAPI(String url,String tb_method,Map<String, String> params) throws IOException {
		params.put("method", tb_method);
		params.put("app_key", app_key);
		params.put("sign_method", "md5");
		params.put("format", "json");
		params.put("v", "2.0");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		params.put("timestamp", df.format(new Date()));
		String sign = signTopRequest(params,tb_secret,"md5");
		params.put("sign", sign);

		String	resultString = HttpClientUtil.doPost(url,params);
		return StringUtils.isNotBlank(resultString) ? JSONObject.parseObject(resultString) : new JSONObject();
	}

	/**
	 * 多麦联盟接口
	 * @param url API接口路径
	 * @param params 业务参数
	 * @return
	 */
	public static Object duomaiAPI(String url,Map<String, String> params) {
		params.put("site_id", site_id);
		params.put("aid", track_aid);

//		String	resultString = HttpClientUtil.doGet(url+getParams(params));
		return url+getParams(params);
	}
	/**
	 * 喵有券接口
	 * @param url API接口路径
	 * @param params 业务参数
	 * @return
	 */
	public static JSONObject miaoyouquanAPI(String url,Map<String, String> params) {
		params.put("apkey", apkey);
		if(url.equals(getpdditem)){
			params.put("pdname", pdname);//是否是搜索拼多多
		}
		String	resultString = HttpClientUtil.doGet(url+getParams(params));
		return StringUtils.isNotBlank(resultString) ? JSONObject.parseObject(resultString) : new JSONObject();
	}
	
	/**
	 * 折淘客接口
	 * @param url API接口路径
	 * @param params 业务参数
	 * @return
	 */
	public static JSONObject zetaokeAPI(String url,Map<String, String> params) {
		params.put("appkey", appkey);
		String	resultString = HttpClientUtil.doGet(url+getParams(params));
		return StringUtils.isNotBlank(resultString) ? JSONObject.parseObject(resultString) : new JSONObject();
	}
	
	/**
	 * 折淘客接口
	 * @param url API接口路径
	 * @param params 业务参数
	 * @return
	 */
	public static String beian(String url,Map<String, String> params) {
		return  HttpClientUtil.doGet(url+getParams(params));
	}
	
	public static String getParams(Map<String, String> map) {
		String result = "";
		try {
			TreeMap<String, String> treeMap = new TreeMap<>(map);

			// 构造签名键值对的格式
			StringBuilder sb = new StringBuilder();
			Iterator<Entry<String, String>> iterator = treeMap.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				String key = entry.getKey();
				String val = entry.getValue();
				//String val = URLEncoder.encode(entry.getValue(), "utf8");
				sb.append(key).append("=").append(val).append("&");
			}
			result = StringUtils.removeEnd(sb.toString(), "&");
			System.out.println("sb:" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String getDuoduoParams(Map<String, String> map) {
		String result = "";
		try {
			Map<String, String> params = new TreeMap<String, String>(
				new Comparator<String>() {
					public int compare(String obj1, String obj2) {
						// 升序排序
						return obj1.compareTo(obj2);
					}
			});
			TreeMap<String, String> treeMap = new TreeMap<>(map);

			// 构造签名键值对的格式
			StringBuilder sb = new StringBuilder();
			Iterator<Entry<String, String>> iterator = treeMap.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				String key = entry.getKey();
				String val = entry.getValue();
				//String val = URLEncoder.encode(entry.getValue(), "utf8");
				sb.append(key).append(val);
			}
			result = sb.toString();
			System.out.println("sb:" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	public static String signTopRequest(Map<String, String> params, String secret, String signMethod) throws IOException {
		// 第一步：检查参数是否已经排序
		String[] keys = params.keySet().toArray(new String[0]);
		Arrays.sort(keys);

		// 第二步：把所有参数名和参数值串在一起
		StringBuilder query = new StringBuilder();
		if (Constants.SIGN_METHOD_MD5.equals(signMethod)) {
			query.append(secret);
		}
		for (String key : keys) {
			String value = params.get(key);
				query.append(key).append(value);
		}

		// 第三步：使用MD5/HMAC加密
		byte[] bytes;
			query.append(secret);
			bytes = encryptMD5(query.toString());

		// 第四步：把二进制转化为大写的十六进制(正确签名应该为32大写字符串，此方法需要时使用)
		return byte2hex(bytes);
	}
	public static String byte2hex(byte[] bytes) {
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				sign.append("0");
			}
			sign.append(hex.toUpperCase());
		}
		return sign.toString();
	}
}
